<script setup>
import {User, Lock} from '@element-plus/icons-vue'
import {ref, watch} from 'vue'
import {sysUserLoginService, sysUserRegisterService} from "@/api/sys_user.js";
import {useUserStore} from "@/stores";
import {useRouter} from "vue-router";

const isRegister = ref(false)
const form = ref()
// 注册-提交的form对象
const formModel = ref({
  account: '',   // 账号
	password: '',   // 密码
	rePassword: '' // 确认密码
})
// 表单的校验规则
const rules = {
	// required：非空校验
	// trigger：如何触发
	// min：最小长度校验
	// max：最大长度校验
	// message：提示信息
	// pattern：正则校验
	// validator：自定义校验
  account: [{
		required: true,
		message: '请输入用户名',
		trigger: 'blur'
	}, {
		min: 5,
		max: 10,
		message: '长度在 5 到 10 个字符',
		trigger: 'blur'
	}],
	// 密码
	password: [{
		required: true,
		message: '请输入密码',
		trigger: 'blur'
	}, {
		pattern: /^\S{6,15}$/,
		message: "密码必须是 6-15 位的非空字符"
	}],
	// 确认密码
	rePassword: [{
		required: true,
		message: '请再次输入密码',
		trigger: 'blur'
	}, {
		pattern: /^\S{6,15}$/,
		message: "密码必须是 6-15 位的非空字符"
	}, {
		// rule：当前校验规则相关信息
		// value：要校验的值
		// callback：回调函数，callback()：校验成功
		// callback：回调函数，callback(new Error(错误信息))：校验失败
		// 就是成功也要掉用，不让会阻塞
		validator: (rule, value, callback) => {
			value !== formModel.value.password ? callback(new Error("两次输入的密码不一致")) : callback()
		},
		trigger: "blur"
	}]
}

// 注册
const register = async () => {
	// 预校验
	await form.value.validate()
	// 发请求
	await sysUserRegisterService(formModel.value)
	ElMessage.success("注册成功")
	// 切换登录
	isRegister.value = false
}

const userStore = useUserStore()
const router = useRouter()

// 登录
const login = async () => {
	// 预校验
	await form.value.validate()
	// 发请求
	const res = await sysUserLoginService(formModel.value)
	// 存储token
	userStore.setToken(res.data)
	ElMessage.success("登录成功")
	// 跳到首页
	await router.push('/')
}

// 切换时重置表单信息
watch(isRegister, () => {
	formModel.value = {
		userName: '',
		password: '',
		rePassword: ''
	}
})
</script>

<template>
	<!--
		1. 结构相关
			el-row 和 el-col 用于布局
			el-row 表示一行，一行分成 24 份
			el-col 表示列，
				:span="12"  代表在一行中，占12份（50%）
				:span="6"   代表在一行中，占6份（25%）
				:offset="3" 代表在一行中，左侧margin份数
			el-form             表示一个表单
			el-form-item        表示一个表单域（也可以理解为一行）
		2. 校验相关
			el-form ==> :model="ruleForm"       绑定整个form数据对象
			el-form ==> :rules="rules"          绑定整个rule规则对象
			el-input ==> v-model="ruleForm.xx"  给表单项，绑定 form 的子属性
			el-form-item ==> prop="xxx"         配置生效的是哪个 rule 校验规则
	-->
	<el-row class="login-page">
		<el-col :span="12" class="bg"></el-col>
		<el-col :span="6" :offset="3" class="form">
			<!-- 注册相关的表单 -->
			<el-form
					:model="formModel"
					:rules="rules"
					ref="form"
					size="large"
					autocomplete="off"
					v-if="isRegister"
			>
				<el-form-item>
					<h1>注册</h1>
				</el-form-item>
				<el-form-item prop="account">
					<el-input
							:prefix-icon="User"
							placeholder="请输入用户名"
							v-model="formModel.account"
					></el-input>
				</el-form-item>
				<el-form-item prop="password">
					<el-input
							:prefix-icon="Lock"
							type="password"
							placeholder="请输入密码"
							v-model="formModel.password"
					></el-input>
				</el-form-item>
				<el-form-item prop="rePassword">
					<el-input
							:prefix-icon="Lock"
							type="password"
							placeholder="请输入再次密码"
							v-model="formModel.rePassword"
					></el-input>
				</el-form-item>
				<el-form-item>
					<el-button
							class="button"
							type="primary"
							auto-insert-space
							@click="register"
					>
						注册
					</el-button>
				</el-form-item>
				<el-form-item class="flex">
					<el-link type="info" :underline="false" @click="isRegister = false">
						← 返回
					</el-link>
				</el-form-item>
			</el-form>
			<!-- 登录相关的表单 -->
			<el-form
					:model="formModel"
					:rules="rules"
					ref="form"
					size="large"
					autocomplete="off"
					v-else
			>
				<el-form-item>
					<h1>登录</h1>
				</el-form-item>
				<el-form-item prop="account">
					<el-input
							v-model="formModel.account"
							:prefix-icon="User"
							placeholder="请输入用户名"
					></el-input>
				</el-form-item>
				<el-form-item prop="password">
					<el-input
							v-model="formModel.password"
							name="password"
							:prefix-icon="Lock"
							type="password"
							placeholder="请输入密码"
					></el-input>
				</el-form-item>
				<el-form-item class="flex">
					<div class="flex">
						<el-checkbox>记住我</el-checkbox>
						<el-link type="primary" :underline="false">忘记密码？</el-link>
					</div>
				</el-form-item>
				<el-form-item>
					<el-button
							class="button"
							type="primary"
							auto-insert-space
							@click="login"
					>登录
					</el-button
					>
				</el-form-item>
				<el-form-item class="flex">
					<el-link type="info" :underline="false" @click="isRegister = true">
						注册 →
					</el-link>
				</el-form-item>
			</el-form>
		</el-col>
	</el-row>
</template>

<style lang="scss" scoped>
.login-page {
	height: 100vh;
	background-color: #fff;

	.bg {
		background: url('@/assets/logo_big.png') no-repeat 60% center / 240px auto,
		url('@/assets/login_bg.jpg') no-repeat center / cover;
		border-radius: 0 20px 20px 0;
	}

	.form {
		display: flex;
		flex-direction: column;
		justify-content: center;
		user-select: none;

		.title {
			margin: 0 auto;
		}

		.button {
			width: 100%;
		}

		.flex {
			width: 100%;
			display: flex;
			justify-content: space-between;
		}
	}
}
</style>